#pragma once
#include <d3d9.h>
#include <d3dx9.h>
#include <vector>
#include <cmath>
#include <fstream>
#include "../utility/vertex.h"
#include "../utility/geometry.h"
#include "../utility/Gets.h"
#include "../utility/light.h"
#include "../shaderMgr.h"
#include "../textureMgr.h"

using namespace std;


const int	TrunkCount  = 1 + 2 + 4 + 8;
const int	TreeHeight   = 4;

class cTreeTrunk
{
public:
	cTreeTrunk();
	void Render(LPDIRECT3DDEVICE9 pDevice9,
				LPDIRECT3DVERTEXBUFFER9 pVB,
				LPDIRECT3DINDEXBUFFER9 pIB,
				ID3DXEffect* pEffect);
	float GetHeight();
	D3DXMATRIX SetWorldMat();
public:
	UINT vertexOffset,indexOffset;
	D3DXMATRIX m_matToWorld;
	D3DXMATRIX m_matToParent;

	float m_fHeight,m_fRadius;
	cTreeTrunk* pParentTrunk;
	cTreeTrunk* pFChildTrunk;
	cTreeTrunk* pSChildTrunk;
public:
	void Release();
};

class cTree
{
public:
	cTree():vertexOffset(0),indexOffset(0){}
	void OnInit(float inHeight,float inRaidus,D3DXVECTOR3 vec);
	void Render();
	void CreateTreeRoot(float inHeight,float inRadius,D3DXVECTOR3 vec);
	void CreateTree(cTreeTrunk* pTrunk,float inHeight,float inRadius,int iTreeHeight);
	void Release();
private:
	void SetTreeTrunk(cTreeTrunk* pTreeTrunk,float inHeight,float inRadius, bool treeEnd = false);
private:
	UINT vertexOffset;
	UINT indexOffset;

	LPDIRECT3DDEVICE9 m_pDevice9;
	LPDIRECT3DVERTEXBUFFER9 m_pVB;
	LPDIRECT3DINDEXBUFFER9 m_pIB;
	cShaderMgr* m_pShaderMgr;
	cTextureMgr* m_pTextureMgr;

	cTreeTrunk* m_pRootTrunk;
};

class cTreeBuilder
{
public:
	cTreeBuilder(){}
	void OnInit(string treelocation,DWORD dwNum);
	void Render();
	void Update(float dt);
	void Release();
private:
	vector<cTree*> vecTree;
	cShaderMgr* m_pShaderMgr;
	cTextureMgr* m_pTextureMgr;
};


//geometry for tree
//center0 is the upper center

const int TreeBaseCircle	= 21;
const int TreeCircleVerices	= TreeBaseCircle + 1;
const int TreeTrunkVertices = (TreeBaseCircle + 1) * 2 + 2;
const int TreeTrunkIndices  = TreeBaseCircle*3*2+TreeBaseCircle*2*3;
const int TreePrimCount		= TreeBaseCircle*2*2;
const float TreeRadiusScale = 0.7;
const float TreeHeightScale = 0.85;

void CreateTreeTrunk(vector<D3DXVECTOR3>& vecTree,vector<DWORD>& vecIndex,
	float inHeight,float inRadius,bool treeEnd);
